import {Component, ElementRef, inject, Input, OnChanges, OnInit, SimpleChanges, ViewChild} from '@angular/core';
import {LoopdataService} from '../../services/loopdata.service';
import {Graph} from '@antv/x6';
import {VirtualLoopData} from '../../models/svgdata';
import {drawConfigType} from '../types/draw-config.type';
import {heightCompute} from '../tools/draw-antv-graph';
import Konva from 'konva';
import {konvaRender} from '../tools/draw-konva-graph';

@Component({
  selector: 'app-konva-graph',
  standalone: false,
  templateUrl: './konva-graph.component.html',
  styleUrl: './konva-graph.component.css'
})
export class KonvaGraphComponent implements OnInit, OnChanges {
  @Input() dataType!: number;
  @ViewChild('graphContainer', {static: true}) graphContainer!: ElementRef;
  private loopDataService = inject(LoopdataService);
  private stage!: Konva.Stage;
  private data!: VirtualLoopData;

  private canvasSize: { width: number; height: number } = {width: 1015, height: 0};
  private moduleSize: { width: number; height: number } = {width: 220, height: 0};

  private shapeSoftStrapMap = new Map<string, string[]>();
  private loopBranchVisibilityMap = new Map<string, boolean>();

  private drawDefaultConfig: drawConfigType = {
    baseDrawConfig: {
      moduleDistance: 700,
      font: {
        small: 8,
        normal: 11,
      },
      color: {
        primary: '#00367a',
        moduleBorderColor: '#27cef7',
        accent: '#25ccf7',
        text: '#ffffff',
        dashedLine: '#000000',
      }
    },
    loopBranchConfig: {
      lineColor: '#25ccf7',
      textColor: '#ffffff',
      textSize: 8,
      lineDistance: 700,
    }
  }


  private drawProps = {
    drawConfig: this.drawDefaultConfig,
    moduleSize: this.moduleSize
  }

  ngOnInit() {
    this.loadData(this.dataType)
  }

  ngOnChanges(changes: SimpleChanges) {
    this.loadData(changes['dataType'].currentValue);
  }

  // ngOnDestroy() {
  //   if (this.graph) {
  //     this.graph.dispose();
  //   }
  // }

  private initGraph() {
    const rect = this.graphContainer.nativeElement.getBoundingClientRect();
    this.stage = new Konva.Stage({
      container: this.graphContainer.nativeElement,
      width: rect.width,
      height: rect.height,
    });
    this.stage.on('wheel', (e) => {
      e.evt.preventDefault(); // 阻止页面滚动

      const scaleBy = 1.05; // 每次缩放倍数
      const oldScale = this.stage.scaleX();
      const pointer = this.stage.getPointerPosition();

      // 当前鼠标位置对应的舞台坐标
      const mousePointTo = {
        x: (pointer!.x - this.stage.x()) / oldScale,
        y: (pointer!.y - this.stage.y()) / oldScale,
      };

      // 滚轮向下缩小，向上放大
      const direction = e.evt.deltaY > 0 ? 1 : -1;
      const newScale = direction > 0 ? oldScale / scaleBy : oldScale * scaleBy;

      this.stage.scale({ x: newScale, y: newScale });

      // 缩放时保持鼠标指针指向位置不变
      const newPos = {
        x: pointer!.x - mousePointTo.x * newScale,
        y: pointer!.y - mousePointTo.y * newScale,
      };
      this.stage.position(newPos);

      this.stage.batchDraw();
    });

    // this.setupNodeEventListeners();
  }

  private renderGraph() {
    if (this.data && this.graphContainer) {
      this.graphContainer.nativeElement.innerHTML = '';
      // // 清空之前的状态映射
      // this.shapeSoftStrapMap.clear();
      // this.loopBranchVisibilityMap.clear();
      // if (this.graph) {
      //   this.graph.dispose();
      // }
      this.initGraph()
      konvaRender(this.stage, this.data, this.canvasSize, this.moduleSize, this.drawProps)
    }
  }

  loadData(dataType: number) {
    this.loopDataService.getLoopData(dataType).subscribe({
      next: (data) => {
        this.data = data;
        this.moduleSize.height = heightCompute(data);
        this.canvasSize.height = this.moduleSize.height + 100;
        console.time('konva render')
        this.renderGraph();
        console.timeEnd('konva render')
      },
      error: (err) => {
        console.error('数据加载失败', err);
      }
    })
  }

}
